// 2025/4/4
// https://leetcode.cn/problems/string-to-integer-atoi/description/
// 字符串转换整数

class Solution {
    public:
        int myAtoi(string s) {
            int n = s.size(), ans = 0, i = 0;
            while(i < n && s[i] == ' ')
                i++;
            if(s[i] == '-')
            {
                if(i > 0 && s[i - 1] == '+') return 0;
                i++;
                while(i < n && ('0' <= s[i] && s[i] <= '9'))
                {
                    int tmp = s[i++] - '0';
                    if(ans < (INT_MIN + tmp) / 10)
                        return INT_MIN;
                    ans *= 10;
                    ans -= tmp;
                }
            }
            else
            {
                if(s[i] == '+') i++;
                while(i < n && ('0' <= s[i] && s[i] <= '9'))
                {
                    int tmp = s[i++] - '0';
                    if(ans > (INT_MAX - tmp) / 10)
                        return INT_MAX;
                    ans *= 10;
                    ans += tmp;
                }
            }
            return ans;
        }
    };